var host= "http://dr.kuyuntech.com/DrAgriculture-0.1";
$(document).ready(function(){

	function Cart(){
		//创建购物车
		this.setCart = function(_callback){
			$.ajax({
				type : "get",
				url  : host + "/terminal/shoppingCart/list",
				data : {
					pageSize : 20
				},
				dataType: "json",
				xhrFields: {
					withCredentials: true	//跨域名请求。XHR：XMLHttpRequest (XHR) ，基于XML技术的Http请求
		        },
		        crossDomain: true,
		        contentType: "application/x-www-form-urlencoded",//表单提交
				success : function(response){
		            if(response.code == 2000){
		            	var _html = "";
		            	for(var i=0; i<response.data.shoppingCarts.length; i++){
		            		a = changePrice(response.data.shoppingCarts[i].goods.price);
		            		_html += '<li code="'+ response.data.shoppingCarts[i].code +'"><div class="checkbox_olone"><img src="image/未选中.png"/></div>' 
						        + '<div class="purchase_information">'
							    + '<p class="productDescription">' + response.data.shoppingCarts[i].goods.title + '</p>'
							    + '<dl>'
								+ '<dt><img src="' + response.data.shoppingCarts[i].goods.defaultImage + '"/></dt>'
								+ '<dd>'
								+ '<p class="unitPrice">¥' + a + '</p>'
								+ '<i style="display:none;">' + response.data.shoppingCarts[i].goods.postFee + '</i>'
								+ '<p>'
								+ '<input type="button" class="subtract" value="-" />'
								+ '<span class="num">' + response.data.shoppingCarts[i].num + '</span>'
								+ '<input type="button" class="add" value="+"/>'
								+ '</p>'
								+ '</dd>'
							    + '</dl>'
						        + '</div>'
						        + '<div class="delete"><img src="image/垃圾桶 删除.png"/></div>'
					            + '</li>';
		            	}
					    $(".full_cart ul").append(_html);        
		            }
		            _callback();
				}
			});
		}
		
		//单选物品
		this.aChoose = function(dom){
			$(dom).each(function(i,ele){
				$(this).on('touchstart',function(){
					if($(this).children().attr("src") == "image/选中.png"){
						$(this).children().attr("src","image/未选中.png");  //打勾
						$(".checkbox_all").children().attr("src","image/未选中.png"); //将全选的勾去掉
						createCart.totalPrice();					//计算总价格
					}else{
						$(this).children().attr("src","image/选中.png");					//去勾
						createCart.totalPrice();					//计算总价格
					}
					//判断是否有选中商品
					var a = true;
					$(dom).each(function(i,ele){
						if($(this).children().attr("src") == "image/选中.png"){
							a = false;
						}
					});
					if(a == true){
						$('#postFee').text("不含运费");
					}
				});
			});
		}
		
		//全选物品
		this.allChoose = function(dom,clickDom){
			$(clickDom).children().on("touchstart",function(){
				var imgSrc = $(clickDom).children().attr("src");
				if( imgSrc == "image/未选中.png"){
					$(clickDom).children().attr("src","image/选中.png");
					$(dom).each(function(i,ele){
						if($(this).children().attr("src") == "image/未选中.png"){
							$(this).children().attr("src","image/选中.png");
							createCart.totalPrice();            //计算总价格
						}
					})
				}else{
					$(clickDom).children().attr("src","image/未选中.png");
					$(dom).each(function(i,ele){
						if($(this).children().attr("src") == "image/选中.png"){
							$(this).children().attr("src","image/未选中.png");
							createCart.totalPrice();            //计算总价格
						}
					})
				}
			})
		}
		
		//添加商品数量
		this.addNum = function(){
			$('.add').each(function(){
				$(this).on('touchstart',function(){
					var goodsNum = $(this).prev().text();
					goodsNum++;
					if(goodsNum <= 1){
						goodsNum = 1;
						$(this).css("border","1px solid rgb(227,227,227)");
					}else{
						$(this).prev().prev().css("border","1px solid #333");
					}
					if(goodsNum >= 200){
						goodsNum = 200;
						$(this).prev().text(goodsNum);
					}
					$(this).prev().text(goodsNum);
					createCart.totalPrice();		//计算总价格
					//添加商品数量，将商品数目发给后台
					var cartCode = $(this).parents("li").attr("code");
					
					$.ajax({
						type : "post",
						dataType: "json",
						xhrFields: {
							withCredentials: true	//跨域名请求。XHR：XMLHttpRequest (XHR) ，基于XML技术的Http请求
				        },
				        crossDomain: true,
				        contentType: "application/x-www-form-urlencoded",//表单提交
				        data : {
				        	num : goodsNum,
							code : cartCode
						},
				        url  : host + "/terminal/shoppingCart/update",
						success : function(response){
							console.log(response)
				            if(response.code == 2000){
				            	 console.log("ok");       
				            }
						}
					});
				});
			})
		}
		
		//减少商品数量
		this.reduceNum = function(){
			
			$('.subtract').each(function(){
				var goodsNum = $(this).next().text();
				if(goodsNum <= 1){
					goodsNum = 1;
					$(this).css("border","1px solid rgb(227,227,227)");
				}else{
					$(this).css("border","1px solid #333");
				}
				$(this).on('touchstart',function(){
					var goodsNum = $(this).next().text();
					goodsNum--;
					if(goodsNum <= 1){
						goodsNum = 1;
						$(this).css("border","1px solid rgb(227,227,227)");
					}else{
						$(this).css("border","1px solid #333");
					}
					$(this).next().text(goodsNum);
					createCart.totalPrice();		//计算总价格
					
					//添加商品数量，将商品数目发给后台
					var cartCode = $(this).parents("li").attr("code");
					$.ajax({
						type : "post",
						dataType: "json",
						xhrFields: {
							withCredentials: true	//跨域名请求。XHR：XMLHttpRequest (XHR) ，基于XML技术的Http请求
				        },
				        crossDomain: true,
				        contentType: "application/x-www-form-urlencoded",//表单提交
				        data : {
				        	num : goodsNum,
							code : cartCode
						},
				        url  : host + "/terminal/shoppingCart/update",
						success : function(response){
							console.log(response)
				            if(response.code == 2000){
				            	 console.log("ok");       
				            }
						}
					});
				});
			})
		}
		
		//计算总价格、总运费
		this.totalPrice = function(dom){
			var arr = [];
			var postFeeArr = [];
			$('.checkbox_olone').each(function(i,ele){
				if($(this).children().attr("src") == "image/选中.png"){
					var price = parseInt($(this).next().find(".unitPrice").text().replace("¥",""));
					var num = $(this).next().find(".num").text();	
					var postFee = $(this).parent("li").find("i").text();
					arr.push(price*num);			
					postFeeArr.push(postFee);
				}					
			});
			var allPrice = 0;
			var allPostFee = 0;
			console.log(postFeeArr)
			for(var i=0;i<arr.length;i++){
				allPrice += arr[i];	
				allPostFee += parseInt(postFeeArr[i]);
			}
			//判断是否为运费是否为0
			if(allPostFee == 0){
				allPostFee = "不含运费";
			}else{
				allPostFee = changePrice(allPostFee);
			}
			//计算总额的方式
			if(allPostFee == "不含运费"){
				$('#price').text("¥" + allPrice);
			}else{
				var a = parseFloat(allPrice) + parseFloat(allPostFee);
				$('#price').text("¥" + a);
			}
			$('#postFee').text(allPostFee);
			
			if($('#price').text().length > 4){
				$('#price').css("font-size","12px");
			}else{
				$('#price').css("font-size","15px");
			}
		}
		
		//计算购物车有多少件商品
		this.shoppingCount = function(){
			var cartNum = $(".full_cart ul li").length;
			if(cartNum == 0){
				$(".empty_cart").removeClass("hide");
				$(".to_settle_accounts").css("background","rgb(204,204,204)").text("去结算");
			}else{
				$(".empty_cart").addClass("hide");
				$(".to_settle_accounts").css("background","rgb(25,120,88)").text("去结算(" + cartNum + ")");
			}
		}
		
		//删除购物车里的物品
		this.remove = function(){
			$('.delete').each(function(){
				$(this).on('touchstart',function(){
					var cartCode = $(this).parents("li").attr("code");
					$.ajax({
						type : "post",
						dataType: "json",
						xhrFields: {
							withCredentials: true	//跨域名请求。XHR：XMLHttpRequest (XHR) ，基于XML技术的Http请求
					    },
					    crossDomain: true,
					    contentType: "application/x-www-form-urlencoded",//表单提交
					    data : {
							code : cartCode
						},
					    url  : host + "/terminal/shoppingCart/delete",
						success : function(response){
							console.log(response)
					        if(response.code == 2000){
					            window.location.reload();        
					        }
						}
					});
				})	
			})
		}
		
		//点击结算，获取选中商品，调到支付确认页面
		this.account = function(dom){
			$(".to_settle_accounts").on("touchstart",function(){
				var arr = [];
				$(dom).each(function(i,ele){
					if($(this).children().attr("src") == "image/选中.png"){
						var code = $(this).parent("li").attr("code");   //获取购物车商品的序列号
						arr.push(code);
					}
			    });
			    window.sessionStorage.goods = arr;
			    
			    //用来判断用户是否选择了商品
			    var a = false;
			    $(".checkbox_olone").each(function(){
			    	if($(this).children().attr("src") == "image/选中.png"){
			    		a = true;
			    	}
			    })
			    if(a == true){
			    	location.href = "order_confirmation.html";
			    }
			})	
		}
	}
	
	//实例化对象
	var createCart = new Cart();
	function _callback(){
		createCart.shoppingCount();
		createCart.aChoose(".checkbox_olone");
		createCart.addNum();
		createCart.reduceNum();
		createCart.allChoose(".checkbox_olone",".checkbox_all");
		createCart.remove();
		createCart.account(".checkbox_olone");
		createCart.totalPrice(".checkbox_olone");
	}
	createCart.setCart(_callback);
});

function changePrice(x){
	x = x/100;
	x=Math.round(parseFloat(x)*100)/100;
	var xsd=x.toString().split(".");
	if(xsd.length==1){
		x=x.toString()+".00";
		return x;
    }
	if(xsd.length>1){
		if(xsd[1].length<2){
		    x=x.toString()+"0";
		}
		return x;
    }
	return x;
}